/* Fix CSS
 * http://code.google.com/p/html5andcss3/
 * Author: kael http://weibo.com/loskael
 */
package los.kael.file;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
 * 将传入的StringBuffer 写入到文件
 * 
 * @author kael
 * 
 */
public class FileWriterFromStringBuffer {
	private StringBuffer sb = null;
	private String outputFilename = null;
	private String charset = "UTF-8";
	private OutputStreamWriter out = null;

	/**
	 * 不指定文件名 输出到控制台
	 * 
	 * @param sb
	 */
	public FileWriterFromStringBuffer(StringBuffer sb) {
		this.sb = sb;
		Write();
	}

	/**
	 * 指定文件名
	 * 
	 * @param sb
	 * @param outputFilename
	 */
	public FileWriterFromStringBuffer(StringBuffer sb, String outputFilename) {
		this.sb = sb;
		this.outputFilename = outputFilename;
		Write();
	}

	/**
	 * 指定文件名和编码类型
	 * 
	 * @param sb
	 * @param outputFilename
	 * @param charset
	 */
	public FileWriterFromStringBuffer(StringBuffer sb, String outputFilename, String charset) {
		this.sb = sb;
		this.outputFilename = outputFilename;
		this.charset = charset;
		Write();
	}

	/**
	 * 写入文件
	 */
	private void Write() {
		try {
			if (outputFilename == null) {
				out = new OutputStreamWriter(System.out, charset);
			} else {
				out = new OutputStreamWriter(new FileOutputStream(outputFilename, false), charset);
			}
			sb = new StringBuffer(sb.toString().trim());
			out.write(sb.toString(), 0, sb.length());
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
